import { Component, OnInit } from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {TableUtil} from "../../../../util/table-util";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {API, MsgConstants} from "../../../../constants/constants";
import {MonitorService} from "../../site-monitor/monitor.service";
import {Monitor} from "../../site-monitor/monitor";
import {MsgResult} from "../../../../models/msg-result";
import {SitesService} from "../sites.service";

  declare  var $;

@Component({
  selector: 'app-assign-site',
  templateUrl: './assign-site.component.html'
})
export class AssignSiteComponent implements OnInit{

  monitor : Monitor;

  //设备类型
  codMonitors;

  siteCode :string;

  siteName :string;

  table;

  tableOne;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private responseUtil:ResponseUtil,
    private monitorService : MonitorService,
    private sitesService : SitesService,
    private pageSubject: PageSubject
  ) {
    this.initObject()
  }

  ngOnInit() {
    this.pushPage();
    this.loadSiteMonitor();
    this.initMonitorType();
    this.initOwnDevice();
  }

  /**
   *  生成面包屑
   */
  private pushPage() {
    let path = new Path("站点管理", null);
    this.pageSubject.pushPage("分配设备", "查询", path);
  }

  /**
   * 搜索刷新
   */
  search(){
    this.table.bootstrapTable('refresh');
  }

  /**
   * 站点未分配设备查询
   */
  loadSiteMonitor(){
    this.table = this.tableUtil.load("one_table_monitor",{
      columns:[
        { checkbox: true },
        { field: "id", title:'ID',align:'left',visible:false,switchable:false	},
        { field: "siteCode", title:'站点代码',align:'left',visible:false,switchable:false },
        { field: "snCode",title:'设备编号' ,align:'left'},
        { field: "monitorName" ,title:'设备类型',align:'left'},
        { field: "siteName", title:'站点名称',align:'left'},
        // { field: "ccid" ,title:'CCID',align:'left',width: 70},
        { field: "receiveTime",title:'最新接收时间' ,align:'left',sortName:"RECEIVETIME",sortable:true},
        { field: "clientipinf",title:'通讯地址' ,align:'left'},
        { field: "mPhone",title:'手机号码' ,align:'left'},
        { field: "status" ,title:'设备状态',align:'left' ,formatter :this.statusFormat},
        // { field: "remark",title:'说明' ,align:'left',width: 150},
        { field: "transMode",title:'数据传输方式' ,align:'left',formatter :this.yesOrNoFormat},
        { field: "arithmeticType",title:'数据算法模式' ,align:'left',formatter :this.arithmeticTypeFormat},
        { field: "createDate",title:'创建时间' ,align:'left'},
      ],
      idField:"id",
      sidePagination:'server',
      pagination:true,
      pageNumber:1,
      pageSize:15,
        pageList: [10,15, 50],
      paginationPreText:"上一页",
      paginationNextText:"下一页",
      paginationLoop:false,//是否开启循环分页
      singleSelect:true,//单选
      clickToSelect:true,//点击选中
      toolbar:".one-operation",
      url:API.siteMonitorPageListV2,
      method:'post',
      //传递附加参数
      queryParams:(params) => {
        params.siteName = $("#siteName").val();
        params.snCode = $("#snCode").val();
        params.monitorCode = $("#monitorCode").val();
        params.ccid = $("input[name='isSiteName']:checked").val();
        return params;
      },
      //返回数据处理器
      responseHandler:(result)=>{
        return this.responseUtil.bsPageHandler(result,(result)=>{
          result.data.rows.forEach(function (value) {
            value.createDate = value.createDate || '';
            value.updateDate = value.updateDate || '';
          });
        });
      },
      height:400,//table高度
      sortable:true,
      order:'asc',
      sortName:'UPDATEDATE',
      classes:"table table-hover",
      striped:true,//隔行变色
      mobileResponsive:true//响应式
    });
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private statusFormat(value,row,index){
    if(value == '0'){
      return "停用";
    }
    if(value == '1'){
      return "正常";
    }
    if(value == '2'){
      return "故障";
    }
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value,row,index){
    if(value == '1'){
      return "gprs";
    }
    if(value == '2'){
      return "lora";
    }
    if(value == '3'){
      return "nb";
    }
  }
  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private arithmeticTypeFormat(value,row,index){
    if(value == '0'){
      return "设备自测数据";
    }
    if(value == '1'){
      return "设备自测+算法（设备必须有数）";
    }
    if(value == '2'){
      return "设备自测+算法（设备可无数）";
    }
  }

  /**
   * 初始化某站点已拥有的设备
   */
  private initOwnDevice(){
    if(!!this.route.snapshot.params['addSiteId']){
      let id = this.route.snapshot.params['addSiteId'];
      this.getSiteInfo(id);
    }else{
      let id = this.route.snapshot.params['id'];
      this.getSiteInfo(id);
    }
  }

  /**
   *  根据id获取站点信息；
   * @param id
   */
  private getSiteInfo(id){
    this.sitesService.getSiteById(id).subscribe(
      result => this.responseUtil.success(result, this.processSiteResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   *  处理站点结果
   * @param result
   */
  private processSiteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //用于显示站点名字
      this.siteName = result.data.siteName;
      this.siteCode = result.data.siteCode;
      this.initFormDataOwnDevice(this.siteCode);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化已分配设备
   * @param siteCode
   */
  private initFormDataOwnDevice(siteCode){
    this.tableOne = this.tableUtil.load("one_table_ownDevice",{
      columns:[
        // { checkbox: true },
        { field: "id", title:'ID',align:'left',visible:false,switchable:false	},
        { field: "siteCode", title:'站点代码',align:'left',visible:false,switchable:false },
        { field: "snCode",title:'设备编号' ,align:'left'},
        { field: "monitorName" ,title:'设备类型',align:'left'},
        { field: "siteName", title:'站点名称',align:'left'},
        { field: "receiveTime",title:'最新接收时间' ,align:'left',sortName:"RECEIVETIME",sortable:true},
        { field: "clientipinf",title:'通讯地址' ,align:'left'},
        { field: "mPhone",title:'手机号码' ,align:'left'},
        { field: "status" ,title:'设备状态',align:'left' ,formatter :this.statusFormat},
        { field: "transMode",title:'数据传输方式' ,align:'left',formatter :this.yesOrNoFormat},
        { field: "arithmeticType",title:'数据算法模式' ,align:'left',formatter :this.arithmeticTypeFormat},
        { field: "createDate",title:'创建时间' ,align:'left'},
        { field: 'operate', title: '操作', align: 'center', events: this.operateEvents,  formatter: this.operateFormatter}
      ],
      idField:"id",
      sidePagination:'server',
      pagination:true,
      pageNumber:1,
      pageSize:15,
      pageList: [10,15, 50],
      paginationPreText:"上一页",
      paginationNextText:"下一页",
      paginationLoop:false,//是否开启循环分页
      singleSelect:true,//单选
      clickToSelect:true,//点击选中
      toolbar:".one-operation",
      url:API.siteMonitorPageListV2,
      method:'post',
      //传递附加参数
      queryParams:(params) => {
        params.siteCode = siteCode;
        return params;
      },
      //返回数据处理器
      responseHandler:(result)=>{
        return this.responseUtil.bsPageHandler(result,(result)=>{
          result.data.rows.forEach(function (value) {
            value.createDate = value.createDate || '';
            value.updateDate = value.updateDate || '';
          });
        });
      },
      height:300,//table高度
      sortable:true,
      order:'asc',
      sortName:'UPDATEDATE',
      classes:"table table-hover",
      striped:true,//隔行变色
      mobileResponsive:true//响应式
    });
  }


  private operateFormatter(value, row, index) {
    return [
      '<a class="remove" href="javascript:void(0)" title="Remove">',
      '<i class="glyphicon glyphicon-remove"></i>',
      '</a>'
    ].join('');
  }

  operateEvents = {
    'click .remove': function (e, value, row, index) {
      this.updateSiteMonitor(row.id, row.snCode, row.monitorCode);
    }.bind(this)
  };

  /**
   * 修改站点已分配设备
   *  1.点击删除操作时，修改该设备的站点为空，状态为停用，
   *  2.同时，该设备会从已分配列表转化到未分配列表中
   * @param id
   * @param snCode
   * @param monitorCode
   */
  private updateSiteMonitor (monitorId, snCode, monitorCode){
    if (!monitorId) {
      this.dialogService.modalInfo("请选择一条信息！", this.search);
    }
    this.monitor.id= monitorId;
    this.monitor.status = "3";
    this.monitor.siteCode = "";
    this.monitor.snCode = snCode;
    this.monitor.monitorCode = monitorCode;
    this.monitorService.siteMonitorEdit(this.monitor).subscribe(
      result => this.responseUtil.success(result, this.processEditMonitorResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   *  处理修改结果
   * @param result
   */
  private processEditMonitorResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.tableOne.bootstrapTable('refresh');
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化设备类型，下拉框
   */
  private initMonitorType(){
    this.monitorService.getMonitor().subscribe(
      result => this.responseUtil.success(result ,this.processMonitorResult),
      message => this.responseUtil.error(message)
    )
  }

  /**
   * 处理查询结果
   * @param result
   */
  private processMonitorResult =(result :MsgResult)=>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.codMonitors = result.data;
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消分配
   */
  cancelAssignSite() {
    if(!!this.route.snapshot.params['addSiteId']){
      this.router.navigate(['../add'], {relativeTo: this.route});
    }else{
      this.router.navigate(['..'], {relativeTo: this.route});
    }
  }

  /**
   * 判断是直接分配还是添加分配
   */
  saveAssignSite(){
    if(!!this.siteCode){
      this.isAssignSite(this.siteCode);
    }else{
      return this.dialogService.modalInfo("请选择一条信息！");
    }
  }


  /**
   * 保存分配的设备
   */
  isAssignSite(siteCode) {
    let rows = this.table.bootstrapTable('getSelections');
    if (!rows[0]) {
      return this.dialogService.modalWarn("请选择一条消息！");
    }
    let id = this.tableUtil.getId(rows[0]);
    //设备编号
    let snCode = this.tableUtil.getCloumn(rows[0], "snCode");
    //设备类型
    let monitorCode = this.tableUtil.getCloumn(rows[0], "monitorCode");

    let params = "siteCode=" + siteCode + "&snCode=" + snCode + "&monitorCode=" + monitorCode;
    if (!!params && !!id) {
      this.monitorService.assignSite(params, id).subscribe(
        result => this.responseUtil.success(result, this.processSiteMonitorResult),
        message => this.responseUtil.error(message)
      );
    }
  }

    /**
     * 处理分配设备的结果
     * @param result
     */
  private processSiteMonitorResult = (result: MsgResult) => {
      if (result && result.code == MsgConstants.MSG_CODE_OK) {
        this.router.navigate(['..'], {relativeTo: this.route});
      }
      if (result && result.code != MsgConstants.MSG_CODE_OK) {
        this.dialogService.info(result.message);
      }
    }

  private initObject() {
    this.monitor = new Monitor();
  }

}
